package ss.lianft.controller;

import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import ss.lianft.model.User;
import ss.lianft.tools.Common;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private SQLManager sqlManager;

    @RequestMapping("mgr")
    public String index(){
        return "user/user";
    }

    @ResponseBody
    @RequestMapping(value="list",method= RequestMethod.GET)
    public Map<String,Object> users(User user,@RequestParam("page") int page,@RequestParam("limit") int limit){
        PageQuery query = new PageQuery();
        if(StringUtils.isBlank(user.getUsername())){
            user.setUsername(null);
        }
        query.setParas(user);
        query.setPageNumber(page);
        query.setPageSize(limit);
        sqlManager.pageQuery("user.list",User.class,query);
        return tableData(query);
    }

    @RequestMapping("create")
    public String preCreate(){
        return "user/userAU";
    }

    @RequestMapping("doAU")
    @ResponseBody
    public String au(User user){
        try {
            if(user.getId()==null) {
                String passwd = user.getPassword();
                passwd = Common.sha256(passwd, user.getUsername());
                user.setPassword(passwd);
                user.setCreateTime(new Date());
                user.setUpdateTime(new Date());
                sqlManager.insert(user);
            }else{
                user.setUpdateTime(new Date());
                sqlManager.updateById(user);
            }
            return "success";
        }catch(Exception e){
            e.printStackTrace();
            return "failed";
        }
    }

    @RequestMapping("view")
    public String view(Model model, @RequestParam("id") int id){
        User user = sqlManager.unique(User.class,id);
        model.addAttribute("user",user);
        return "user/userView";
    }

    @RequestMapping("update")
    public String update(Model model, @RequestParam("id") int id){
        User user = sqlManager.unique(User.class,id);
        model.addAttribute("user",user);
        return "user/userAU";
    }
    @RequestMapping("del")
    public String del(Model model,@RequestParam("id") int id){
        sqlManager.deleteById(User.class,id);
        return "success";
    }
}
